<?php

class UserController extends App_Controller_Action
{

	/**
	 *
	 * @var boolean
	 */
	protected $_requireLogin = false;

	/**
	 * 
	 */
	protected function indexAction()
	{
		$this->_redirect('/');
	}

	/**
	 * 
	 */
	protected function loginAction()
	{
		$auth = Zend_Auth::getInstance();

		if ($auth->hasIdentity())
		{
			$this->_redirect('/');
		}

		$form = new Default_Form_Login();
		$form->setAction($this->view->url());

		if ($this->getRequest()->isPost())
		{
			if ($form->isValid($this->getRequest()->getPost()))
			{
				$adapter = new Zend_Auth_Adapter_DbTable(null, 'user', 'email', 'password', 'SHA1(CONCAT(?, salt))');
				$adapter->setIdentity($form->getValue('email'));
				$adapter->setCredential($form->getValue('password'));

				$result = $auth->authenticate($adapter);
				if ($result->isValid())
				{
					$obj = $adapter->getResultRowObject(null, array('password', 'salt'));
					$auth->getStorage()->write($obj);

					$this->_redirect('/');
				}
				else
				{
					$form->setErrors(array('Wrong email or password'));
				}
			}
		}

		$this->view->form = $form;
	}

	/**
	 * 
	 */
	protected function logoutAction()
	{
		Zend_Auth::getInstance()->clearIdentity();
		Zend_Session::destroy();

		$this->_redirect('/');
	}

	/**
	 * 
	 */
	protected function profileAction()
	{
		$auth = Zend_Auth::getInstance();
		if (!$auth->hasIdentity())
		{
			$this->_helper->redirector->gotoRouteAndExit(array('controller' => 'user', 'action' => 'login'), 'default', 'true');
		}

		$model = new Zend_Db_Table(array('name' => 'user'));
		$row = $model->fetchRow(array('id = ?' => $auth->getIdentity()->id));

		$form = new Default_Form_Profile();
		$form->setAction($this->view->url());

		$form->populate($row->toArray());

		$this->view->form = $form;
	}

}